package com.yaozheng.vocationaltraining.fragment.exam;

import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.adapter.PKCategoryAdapter;
import com.yaozheng.vocationaltraining.bean.HundredQuestionsEncyclopediaItemBean;
import com.yaozheng.vocationaltraining.bean.PKCategoryBean;
import com.yaozheng.vocationaltraining.bean.ScoreBean;
import com.yaozheng.vocationaltraining.bean.UserInfoBean;
import com.yaozheng.vocationaltraining.bean.WinRateBean;
import com.yaozheng.vocationaltraining.fragment.BaseFragment;
import com.yaozheng.vocationaltraining.iview.exam.IPKView;
import com.yaozheng.vocationaltraining.service.exam.LimitedChallengeService;
import com.yaozheng.vocationaltraining.service.exam.PKService;
import com.yaozheng.vocationaltraining.service.impl.exam.LimitedChallengeServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.exam.PKServiceImpl;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.widget.CircleImageView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

/**
 * Created by moon on 2017/11/14.
 */

@EFragment(R.layout.activity_pk)
public class PKFragment extends BaseFragment implements IPKView{
    @ViewById
    GridView gridview;

    PKCategoryAdapter pkCategoryAdapter;
    ArrayList<PKCategoryBean> pkCategoryData = new ArrayList<>();

    @ViewById
    TextView headTitleText;
    @ViewById
    TextView headRightText;

    @ViewById
    TextView jifeng_number_textview;
    @ViewById
    CircleImageView userAvatarImage;
    @ViewById
    TextView username_textview;
    @ViewById
    TextView winning_textview;

    @Bean(PKServiceImpl.class)
    PKService pkService;

    UserInfoBean userInfo;
    WinRateBean bean;

    private BitmapLoader userBitmapLoader;

    public HomeActivity getHomeActivity() {
        return (HomeActivity) getActivity();
    }

    ScoreBean scoreBean;

    @AfterViews
    public void initView() {
        headTitleText.setText("PK赛");
        pkService.init(this);
        userBitmapLoader = new BitmapLoader(Glide.with(this), R.drawable.user_img);

        headRightText.setText("排行榜");
        headRightText.setVisibility(View.VISIBLE);
        headRightText.setTextColor(this.getActivity().
                getResources().getColor(R.color.black));

        pkCategoryAdapter = new PKCategoryAdapter(this.getActivity(),pkCategoryData);
        gridview.setAdapter(pkCategoryAdapter);

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                getHomeActivity().openPKGameCategoryFragment(userInfo.getName(),
                        userInfo.getAvatar(),
                        scoreBean.getQuarter(),
                        bean.getRate(),
                        pkCategoryData.get(i).getId());
            }
        });

        loadWinRate();
        loadUserInfo();
        loadScore();//获取我的积分
        onRefresh();
    }

    @Click(R.id.headRightText)
    public void headRightTextClick() {//打开排行榜界面
        getHomeActivity().openPKRankFragment(userInfo.getName(),
                userInfo.getAvatar(),
                scoreBean.getQuarter(),
                bean.getRate());
    }

    private void loadScore() {
        pkService.loadScore();
    }

    private void loadUserInfo() {
        pkService.getUserInfo();
    }

    private void loadWinRate() {
        pkService.loadWinRate();
    }

    private void onRefresh() {//
        pkService.loadPKCategoryData();
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","categories");
            if (dataList != null) {
                pkCategoryData.clear();

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject jsonObject2 = dataList.getJSONObject(i);

                    PKCategoryBean bean = new PKCategoryBean();
                    bean.setId(jsonObject2.getInt("id"));
                    bean.setName(jsonObject2.getString("name"));
                    bean.setBname(jsonObject2.getString("bname"));
                    bean.setImage(jsonObject2.getString("image"));
                    bean.setAttended(jsonObject2.getInt("attended"));

                    pkCategoryData.add(bean);
                }

                pkCategoryAdapter.setData(pkCategoryData);
                pkCategoryAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    @UiThread
    @Override
    public void responseError(String error) {

    }

    @UiThread
    @Override
    public void winRateSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            JSONObject winRateObject = TypeUtils.getJsonObject(jsonObject, "data","rate");
            if (winRateObject != null && winRateObject.containsKey("rate")) {

                bean = new WinRateBean();
                bean.setUserId(winRateObject.getInt("userId"));
                try {
                    bean.setRate(winRateObject.getInt("rate"));
                } catch (Exception e) {
                    bean.setRate(0);
                }


                if (bean.getRate() != 0){
                    winning_textview.setText(bean.getRate()/ 100.0+"");
                }else {
                    winning_textview.setText("--");
                }

            }else {
                winning_textview.setText("--");
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
            winning_textview.setText("--");
        }
    }

    @UiThread
    @Override
    public void winRateError(String error) {
        winning_textview.setText("--");
    }

    @UiThread
    @Override
    public void userInfoSuccess(JSONObject jsonObject) {
        JSONObject dataJsonObject = TypeUtils.getJsonObject(jsonObject, "data","user");
        userInfo = new UserInfoBean();
        userInfo.setId(dataJsonObject.getInt("id"));
        userInfo.setUserType(dataJsonObject.getInt("userType"));
        userInfo.setName(dataJsonObject.getString("name"));
        //TODO 消息没有填充完毕

        userInfo.setAvatar(dataJsonObject.getString("avatar"));

        //加载图片
        userBitmapLoader.displayImage(userInfo.getAvatar(), userAvatarImage);

        username_textview.setText(userInfo.getName());

    }

    @UiThread
    @Override
    public void userInfoError(String error) {

    }

    @UiThread
    @Override
    public void loadScoreSuccess(JSONObject jsonObject) {
        JSONObject dataJsonObject = TypeUtils.getJsonObject(jsonObject, "data","score");
        scoreBean= new ScoreBean();
        scoreBean.setTotal(dataJsonObject.getInt("total"));
        scoreBean.setQuarter(dataJsonObject.getInt("quarter"));

        jifeng_number_textview.setText(scoreBean.getQuarter()+"");
    }

    @UiThread
    @Override
    public void loadScoreError(String error) {
        jifeng_number_textview.setText("--");
    }
}
